package com.zhentao.filter;

import com.zhentao.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Date 2024/5/10 9:40
 * @Author xdm
 **/
@Component
public class WeMediaLoginFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();


        //1.判断是否是登录操作，如果是登录的话直接放行
        String path = request.getURI().getPath();
        if (path.contains("/login")) {
            return chain.filter(exchange);
        }

        //2.判断token是否正确
        //2.1判断有没有token,没有token,肯定没有登录
        String token = request.getHeaders().getFirst("token");
        if (token == null) {
            //token不存在
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //2.2token已存在 token可能是假的，也有可能过期了

        try {
            Claims claims = AppJwtUtil.getClaimsBody(token);
            //检查是否过期
            int result = AppJwtUtil.verifyToken(claims);
            if (result == 1 || result == 2) {
                //token是过期了
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
            //token是正确的  咱们在执行操作的时候需要用到userId, -token
            Object userId = claims.get("id");
//其他的业务里面要用到这个用户id  现在在过滤器里面
// 把userId放到header里面
            ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders -> {
                httpHeaders.add("userId", userId + "");
            }).build();

//重置header
            exchange.mutate().request(serverHttpRequest).build();
        } catch (Exception e) {
            //token是错误的
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}